package com.xunan.demo.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.xunan.demo.pojo.CommonResult;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 参考文档：https://opendocs.alipay.com/open/00a0ut   开放能力，顺着看  API列表中会告诉你整么调用
 */
@Service
public class AlipayUserService {

    /**
     * 小程序支付宝请求客户端
     */
    @Resource
    AlipayClient alipayMiniAppAlipayClient;

    /**
     * 查询用户的UserId
     *
     * @param userCode    授权码
     * @param refreshCode 刷新令牌。通过该令牌可以刷新access_token
     * @return UserId
     */
    public CommonResult<AlipaySystemOauthTokenResponse> getMiniAppUserInfo(String userCode, String refreshCode) {

        //构建请求
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();

        //选择授权方式
        if (userCode != null) {
            request.setGrantType("authorization_code");
            request.setCode(userCode);
        } else if (refreshCode != null) {
            request.setGrantType("refresh_token");
            request.setRefreshToken(refreshCode);
        } else {
            return new CommonResult<>(false, "缺少授权码或刷新令牌", null);
        }

        //请求结果
        AlipaySystemOauthTokenResponse oauthTokenResponse;
        try {
            oauthTokenResponse = alipayMiniAppAlipayClient.certificateExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return new CommonResult<>(false, "内部错误", null);
        }

        //判断数据信息
        if (oauthTokenResponse.getUserId() == null) {
            return new CommonResult<>(false, "获取失败", oauthTokenResponse);
        } else {
            return new CommonResult<>(true, "正常", oauthTokenResponse);
        }

    }

}
